/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.greenrobot.eventbusperf.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.os.ProcessManager;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.ResourceTable;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.greenrobot.eventbusperf.Test;
import org.greenrobot.eventbusperf.TestFinishedEvent;
import org.greenrobot.eventbusperf.TestParams;
import org.greenrobot.eventbusperf.TestRunner;

/**
 * This activity gets the information from the activity before, sets up the test and starts the test. After it watchs
 * after that, if a test is finished. When a test is finished, the activity appends it on the textview analyse. If all
 * test are finished, it cancels the timer.
 */
public class TestRunnerSlice extends AbilitySlice {

    private TestRunner testRunner;
    private EventBus controlBus;
    private Text textViewResult;
    private TestParams testParams;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_activity_runtests);
        textViewResult = (Text) findComponentById(ResourceTable.Id_textViewResult);
        controlBus = new EventBus();
        testParams = (TestParams) intent.getParams().getParam("params");
        controlBus.register(this);
    }

    @Override
    protected void onActive() {
        super.onActive();
        if (testRunner == null) {
            testRunner = new TestRunner(getApplicationContext(), testParams, controlBus);
            if (testParams.getTestNumber() == 1) {
                textViewResult.append("Events: " + testParams.getEventCount() + "\n");
            }
            textViewResult.append("Subscribers: " + testParams.getSubscriberCount() + "\n\n");
            testRunner.start();
        }

        findComponentById(ResourceTable.Id_buttonCancel).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                onClickCancel(component);
            }
        });
        findComponentById(ResourceTable.Id_buttonKillProcess).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                onClickKillProcess(component);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(TestFinishedEvent event) {
        Test test = event.test;
        String text = test.getDisplayName() + "\n" +
                test.getPrimaryResultMicros() + " micro seconds\n" +
                ((int) test.getPrimaryResultRate()) + "\n";
        if (test.getOtherTestResults() != null) {
            text += test.getOtherTestResults();
        }
        text += "\n";
        textViewResult.append(text);
        if (event.isLastEvent) {
            findComponentById(ResourceTable.Id_buttonCancel).setVisibility(Component.HIDE);
            findComponentById(ResourceTable.Id_textViewTestRunning).setVisibility(Component.HIDE);
            findComponentById(ResourceTable.Id_buttonKillProcess).setVisibility(Component.VISIBLE);
        }
    }

    public void onClickCancel(Component view) {
        // Cancel asap
        if (testRunner != null) {
            testRunner.cancel();
            testRunner = null;
        }
        terminate();
    }

    public void onClickKillProcess(Component view) {
        ProcessManager.kill(ProcessManager.getPid());
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (testRunner != null) {
            testRunner.cancel();
        }
        controlBus.unregister(this);
    }
}
